package com.hardware.controller.category;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hardware.common.R;
import com.hardware.entity.ShopCategory;
import com.hardware.service.category.ShopCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.hardware.utils.RedisConstants.CACHE_CATEGORY_SHOP_KEY;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/shopCategory")
@Slf4j
public class ShopCategoryController {

    @Autowired
    private ShopCategoryService shopCategoryService;

    /**
     * 新增分类
     * @param shopCategory
     * @return
     */
    @PostMapping
    @CacheEvict(value = CACHE_CATEGORY_SHOP_KEY, allEntries = true)
    public R<String> save(@RequestBody ShopCategory shopCategory){
        shopCategoryService.save(shopCategory);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = CACHE_CATEGORY_SHOP_KEY,key = "#page +'_'+ #pageSize")
    public R<Page> page(int page,int pageSize){

        return shopCategoryService.page(page,pageSize);
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = CACHE_CATEGORY_SHOP_KEY, allEntries = true)
    public R<String> delete(Long id){

        shopCategoryService.remove(id);

        return R.success("分类信息删除成功");
    }

    /**
     * 根据id修改分类信息
     * @param shopCategory
     * @return
     */
    @PutMapping
    @CacheEvict(value = CACHE_CATEGORY_SHOP_KEY, allEntries = true)
    public R<String> update(@RequestBody ShopCategory shopCategory){

        shopCategoryService.updateById(shopCategory);

        return R.success("修改分类信息成功");
    }

    /**
     * 根据条件查询分类数据
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = CACHE_CATEGORY_SHOP_KEY)
    public R<List<ShopCategory>> list(){
        //条件构造器
        LambdaQueryWrapper<ShopCategory> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByAsc(ShopCategory::getSort).orderByDesc(ShopCategory::getUpdateTime);

        List<ShopCategory> list = shopCategoryService.list(queryWrapper);
        return R.success(list);
    }
}
